package com.hys.app.job;

import com.hys.app.framework.util.DateUtil;
import com.hys.app.framework.util.JsonUtil;
import com.hys.app.model.base.SettingGroup;
import com.hys.app.model.system.vo.SiteSetting;
import com.hys.app.service.base.service.SettingManager;
import com.hys.app.service.system.SystemLogsManager;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 清理系统日志定时任务
 *
 * @author chopper
 * @version v1.0
 * @since v7.0
 * 2018-07-06 上午4:24
 */
@JobHandler(value = "cleanSystemJobHandler")
@Component
public class CleanSystemJobHandler extends IJobHandler {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    private SettingManager settingManager;

    @Autowired
    private SystemLogsManager systemLogsManager;

    @Override
    public ReturnT<String> execute(String param) throws Exception {

        try {
            //获取站点信息
            String siteSettingJson = settingManager.get(SettingGroup.SITE);
            SiteSetting siteSetting = JsonUtil.jsonToObject(siteSettingJson, SiteSetting.class);
            //如果设置中的月份信息不为空，需要删除几个月之前的日志信息
            if (siteSetting.getMonthNum() != null) {
                //获取当前时间
                Long nowTime = DateUtil.getDateline();
                //获取几个月之前的时间
                Long time = nowTime - (30 * 24 * 60 * 60 * siteSetting.getMonthNum());
                //删除小于这个时间的日志信息
                this.systemLogsManager.deleteByTime(time);
            }
            return ReturnT.SUCCESS;
        } catch (Exception e) {
            logger.error("清理系统日志定时任务出错", e);
            return ReturnT.FAIL;
        }

    }
}
